// Package crons
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2023 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
package crons

import (
	"context"
	"encoding/json"
	"fmt"
	"hotgo/internal/library/cron"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/client"
	"io"
	"strings"
)

func init() {
	cron.Register(StockLive)
}

// StockLive 测试任务（无参数）
var StockLive = &cStockLive{name: "stock_live"}
var StockLiveUrl = "https://apphwhq.longhuvip.com/w1/api/index.php?a=ZhiBoContent&apiv=w33&c=ConceptionPoint&PhoneOSNew=1&index=0&DeviceID=ffffffff-e91e-5efd-ffff-ffffa460846b&VerSion=5.13.0.2&Token=d336f47db0d11c37400313830329564e&"

type StockLiveResp struct {
	Date    string          `json:"date"`
	ErrCode string          `json:"errcode"`
	List    []StockLiveItem `json:"List"`
}
type StockLiveItem struct {
	Comment string  `json:"Comment"`
	Time    int     `json:"Time"`
	Stock   [][]any `json:"Stock"`
}

type cStockLive struct {
	name string
}

func (c *cStockLive) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cStockLive) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	httpClient := client.GetClient()
	response, err := httpClient.Get(ctx, fmt.Sprintf("%s", StockLiveUrl))
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute http.Get err:%+v", err)
		return
	}
	defer response.Body.Close()
	body, err := io.ReadAll(response.Body)
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute io.ReadAll err:%+v", err)
		return err
	}
	var resp StockLiveResp
	err = json.Unmarshal(body, &resp)
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute json.Unmarshal err:%+v", err)
		return err
	}
	if resp.ErrCode == "0" {
		respDate := resp.Date
		for _, emResp := range resp.List {
			var stockCodes []string
			for _, item := range emResp.Stock {
				code, _ := item[0].(string)
				if len(code) != 0 {
					stockCodes = append(stockCodes, code)
				}
			}
			err := service.SysStockLive().Edit(ctx, &sysin.StockLiveEditInp{
				StockLive: entity.StockLive{
					Date:    respDate,
					Comment: emResp.Comment,
					Time:    emResp.Time,
					Stocks:  strings.Join(stockCodes, ","),
				},
			})
			if err != nil {
				parser.Logger.Warning(ctx, "cron CloseOrder Execute service.SysStockZhASpotEm().Edit err:%+v", err)
				continue
			}
		}
	}
	return
}
